package com.jinlejia.erp.ui.house;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityHouseRecordInfoBinding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SheetSelect;
import com.jinlejia.erp.ui.common.SheetWheel;
import com.jinlejia.erp.ui.common.SourceTypeDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.RegexUtils;
import com.weight.CustomToast;
import com.weight.IconToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * \房源录入-基本信息
 */
public class HouseRecordInfoActivity extends AppCompatActivity {



    private ArrayList<Map<String, Object>> houseTypeList = new ArrayList<>();
    private ArrayList<Map<String, Object>> faceList = new ArrayList<>();
    private ArrayList<Map<String, Object>> seeTimeList = new ArrayList<>();
    private ArrayList<Map<String, Object>> entrustSourceList = new ArrayList<>();
    private ArrayList<Map<String, Object>> relationList = new ArrayList<>();

    private ArrayList<Map<String,Object>> housePurpose = new ArrayList<>();
    //住宅室厅卫厨
    private ArrayList<Map<String,Object>> residenceS = new ArrayList<>();
    private ArrayList<Map<String,Object>> residenceT = new ArrayList<>();
    private ArrayList<Map<String,Object>> residenceW = new ArrayList<>();
    private ArrayList<Map<String,Object>> residenceC = new ArrayList<>();
    //公寓室厅卫厨
    private ArrayList<Map<String,Object>> apartmentS = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentT = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentW = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentC = new ArrayList<>();
    //别墅室厅卫厨
    private ArrayList<Map<String,Object>> villaS = new ArrayList<>();
    private ArrayList<Map<String,Object>> villaT = new ArrayList<>();
    private ArrayList<Map<String,Object>> villaW = new ArrayList<>();
    private ArrayList<Map<String,Object>> villaC = new ArrayList<>();

    private String purposedict;
    private String roomDict;
    private String hallDict;
    private String kitchenDict;
    private String toiletDict;
    private String apartment = "";//户型拼接

    JSONObject jsonObject = new JSONObject();

    private ProgressDialog progressDialog;

    private ActivityHouseRecordInfoBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_house_record_info);

        binding.backBtn.setOnClickListener(this::onClick);
        binding.houseType.setOnClickListener(this::onClick);
        binding.houseOrientation.setOnClickListener(this::onClick);
        binding.area.setOnClickListener(this::onClick);
        binding.price.setOnClickListener(this::onClick);
        binding.timeVisit.setOnClickListener(this::onClick);
        binding.sourse.setOnClickListener(this::onClick);
        binding.btPre.setOnClickListener(this::onClick);
        binding.btFinish.setOnClickListener(this::onClick);
        binding.addContact.setOnClickListener(this::onClick);
        binding.delLink.setOnClickListener(this::onClick);
        binding.linkRelation.setOnClickListener(this::onClick);
        binding.housePurpose.setOnClickListener(this::onClick);

        getDiction();
        binding.area.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(".") && dest.toString().length() == 0){
                    return "0.";
                }
                if(dest.toString().contains(".")){
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if(length == 3){
                        return "";
                    }
                }
                return null;
            }
        }});
        binding.price.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(".") && dest.toString().length() == 0){
                    return "0.";
                }
                if(dest.toString().contains(".")){
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if(length == 3){
                        return "";
                    }
                }
                return null;
            }
        }});

        jsonObject.put("rscode", getIntent().getStringExtra("code"));

        if (getIntent().getStringExtra("type").equals("rent")) {
            binding.priceTip.setText("租金:");
            binding.price.setHint("请输入租金(元)");
        } else {
            binding.priceTip.setText("售价:");
            binding.price.setHint("请输入售价(万)");
        }
        progressDialog = new ProgressDialog(HouseRecordInfoActivity.this, "请稍后...");

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.house_purpose:
                final SheetSelect purposesheetSelect = new SheetSelect(this,"用途",housePurpose);
                purposesheetSelect.show();
                purposesheetSelect.setOnSelectListener(new SheetSelect.OnSelectListener() {
                    @Override
                    public void select(Object o) {
                        Map<String, Object> map = (Map<String, Object>) o;
                        purposesheetSelect.dismiss();
                        binding.housePurpose.setText(map.get("valueName").toString());
                        jsonObject.put("purpose", map.get("valuel").toString());
                        if (map.get("valueName").toString().equals("厂房/仓库")||map.get("valueName").toString().equals("商铺")||map.get("valueName").toString().equals("写字楼")){
                            binding.houseType.setText("");
                            jsonObject.remove("room");
                            jsonObject.remove("hall");
                            jsonObject.remove("kitchen");
                            jsonObject.remove("toilet");
                            binding.jslayout.setVisibility(View.GONE);
                        }else{
                            binding.jslayout.setVisibility(View.VISIBLE);
                        }
                        binding.houseType.setText("");
                        jsonObject.remove("room");
                        jsonObject.remove("hall");
                        jsonObject.remove("kitchen");
                        jsonObject.remove("toilet");
                    }
                });
                //todo:用途！！
                break;
            case R.id.house_type:
                if (TextUtils.isEmpty(binding.housePurpose.getText().toString())){
                    CustomToast.showToast(this, "请先选择房屋用途", 1500);
                }else{
                    if (binding.housePurpose.getText().toString().equals("住宅")){
                        SheetWheel sheetWheel = new SheetWheel(this,residenceS,residenceT,residenceW,residenceC);
                        sheetWheel.show();
                        sheetWheel.setOnSelectListener(new SheetWheel.OnSelectListener() {
                            @Override
                            public void select(Map<String, Integer> map) {
                                jsonObject.putAll(map);
                                binding.houseType.setText(map.get("room") + "室" + map.get("hall") + "厅" + map.get("kitchen") + "厨" + map.get("toilet") + "卫" );
                            }
                        });
                    }else if (binding.housePurpose.getText().toString().equals("公寓")){
                        SheetWheel sheetWheel = new SheetWheel(this, apartmentS,apartmentT,apartmentW,apartmentC);
                        sheetWheel.show();
                        sheetWheel.setOnSelectListener(new SheetWheel.OnSelectListener() {
                            @Override
                            public void select(Map<String, Integer> map) {
                                jsonObject.putAll(map);
                                binding.houseType.setText(map.get("room") + "室" + map.get("hall") + "厅" + map.get("kitchen") + "厨" + map.get("toilet") + "卫" );
                            }
                        });
                    }else if (binding.housePurpose.getText().toString().equals("别墅")){
                        SheetWheel sheetWheel = new SheetWheel(this,villaS,villaT,villaW,villaC);
                        sheetWheel.show();
                        sheetWheel.setOnSelectListener(new SheetWheel.OnSelectListener() {
                            @Override
                            public void select(Map<String, Integer> map) {
                                jsonObject.putAll(map);
                                binding.houseType.setText(map.get("room") + "室" + map.get("hall") + "厅" + map.get("kitchen") + "厨" + map.get("toilet") + "卫" );
                            }
                        });
                    }
                }

                break;
            case R.id.house_orientation:
                final SheetSelect orientationSelect = new SheetSelect(HouseRecordInfoActivity.this, "朝向", faceList);
                orientationSelect.show();
                orientationSelect.setOnSelectListener(new SheetSelect.OnSelectListener() {
                    @Override
                    public void select(Object o) {
                        Map<String, Object> map = (Map<String, Object>) o;
                        orientationSelect.dismiss();
                        binding.houseOrientation.setText(map.get("valueName").toString());
                        jsonObject.put("face", map.get("valuel").toString());
                    }
                });
                break;
            case R.id.time_visit:
                final SheetSelect visitSelect = new SheetSelect(HouseRecordInfoActivity.this, "看房时间", seeTimeList);
                visitSelect.show();
                visitSelect.setOnSelectListener(new SheetSelect.OnSelectListener() {
                    @Override
                    public void select(Object o) {
                        Map<String, Object> map = (Map<String, Object>) o;
                        visitSelect.dismiss();
                        binding.timeVisit.setText(map.get("valueName").toString());
                        jsonObject.put("seeTime", map.get("valuel").toString());
                    }
                });
                break;
            case R.id.sourse:

                final SourceTypeDialog sourceTypeDialog = new SourceTypeDialog(HouseRecordInfoActivity.this, entrustSourceList);
                sourceTypeDialog.show();
                sourceTypeDialog.setOnSelectedListener(new SourceTypeDialog.OnSelectedListener() {
                    @Override
                    public void onSelected(Map<String, Object> source1Map, Map<String, Object> source2Map) {
                        sourceTypeDialog.dismiss();
                        binding.sourse.setText(source1Map.get("valueName").toString() + "  " + source2Map.get("valueName").toString());
                        jsonObject.put("entrustSourceType", source1Map.get("valueName"));
                        jsonObject.put("entrustSourceCode", source1Map.get("valuel"));
                        jsonObject.put("entrustSource", source2Map.get("valuel"));
                    }
                });

                break;
            case R.id.bt_pre:
                //上一步
                finish();
                break;
            case R.id.bt_finish:
                //完成
                jsonObject.put("square", binding.area.getText().toString());
                jsonObject.put("name", binding.owenr.getText().toString());
                jsonObject.put("tel", binding.phone.getText().toString());
                jsonObject.put("weixinId", TextUtils.isEmpty(binding.weixin.getText().toString()) ? null : binding.weixin.getText().toString());
                jsonObject.put("spareTel", TextUtils.isEmpty(binding.phoneReserve.getText().toString()) ? null : binding.phoneReserve.getText().toString());
                jsonObject.put("contactName", TextUtils.isEmpty(binding.linkName.getText().toString()) ? null : binding.linkName.getText().toString());
                jsonObject.put("contactTel", TextUtils.isEmpty(binding.linkPhone.getText().toString()) ? null : binding.linkPhone.getText().toString());
                if (TextUtils.isEmpty(jsonObject.getString("purpose"))){
                    CustomToast.showToast(this, "请选择用途", 1500);
                } else if ((TextUtils.isEmpty(jsonObject.getString("room")) && binding.jslayout.getVisibility()== View.VISIBLE) || (TextUtils.isEmpty(binding.houseType.getText().toString()) && binding.jslayout.getVisibility()== View.VISIBLE)) {
                    CustomToast.showToast(this, "请选择户型", 1500);
                } else if (TextUtils.isEmpty(jsonObject.getString("face"))) {
                    CustomToast.showToast(this, "请选择朝向", 1500);
                } else if (TextUtils.isEmpty(jsonObject.getString("square"))) {
                    CustomToast.showToast(this, "请输入面积", 1500);
                } else if (TextUtils.isEmpty(binding.price.getText().toString())) {
                    CustomToast.showToast(this, "请输入价格", 1500);
                } else if (TextUtils.isEmpty(jsonObject.getString("seeTime"))) {
                    CustomToast.showToast(this, "请选择看房时间", 1500);
                } else if (TextUtils.isEmpty(jsonObject.getString("entrustSourceType"))) {
                    CustomToast.showToast(this, "请选择委托来源", 1500);
                } else if (TextUtils.isEmpty(binding.owenr.getText().toString())) {
                    CustomToast.showToast(this, "请输入业主", 1500);
                } else if (TextUtils.isEmpty(binding.phone.getText().toString())) {
                    CustomToast.showToast(this, "请输入业主电话", 1500);
                } else if (!RegexUtils.isMobileSimple(binding.phone.getText().toString())) {
                    CustomToast.showToast(this, "业主手机号格式错误", 1500);
                } else if (!TextUtils.isEmpty(jsonObject.getString("contactName")) || !TextUtils.isEmpty(jsonObject.getString("contactTel")) || !TextUtils.isEmpty(jsonObject.getString("relation"))) {
                    if (TextUtils.isEmpty(jsonObject.getString("contactName"))) {
                        CustomToast.showToast(HouseRecordInfoActivity.this, "请输入联系人姓名", 1500);
                    } else if (TextUtils.isEmpty(jsonObject.getString("relation"))) {
                        CustomToast.showToast(HouseRecordInfoActivity.this, "请选择联系人与客户关系", 1500);
                    } else if (TextUtils.isEmpty(jsonObject.getString("contactTel"))) {
                        CustomToast.showToast(HouseRecordInfoActivity.this, "请输入联系人电话", 1500);
                    } else if (!TextUtils.isEmpty(binding.linkPhone.getText().toString()) && !RegexUtils.isMobileSimple(binding.linkPhone.getText().toString())) {
                        CustomToast.showToast(this, "联系人手机号格式错误", 1500);
                    } else {
                        submit();
                    }
                } else {
                    submit();
                }

                break;
            case R.id.add_contact:
                //添加联系人
                if (!binding.linkLayout.isShown())
                    binding.linkLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.del_link:
                //删除联系人
                CommonDeleteDialog dialog = new CommonDeleteDialog(HouseRecordInfoActivity.this, "删除联系人", "确定删除联系人?");
                dialog.show();
                dialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        binding.linkLayout.setVisibility(View.GONE);
                        binding.linkName.setText("");
                        binding.linkRelation.setText("");
                        binding.linkPhone.setText("");
                        if (jsonObject.containsKey("relation"))
                            jsonObject.remove("relation");
                        if (jsonObject.containsKey("contactTel"))
                            jsonObject.remove("contactTel");
                        if (jsonObject.containsKey("contactName"))
                            jsonObject.remove("contactName");
                    }
                });

                break;
            case R.id.link_relation:
                //选择联系人关系
                final SheetSelect relationSelect = new SheetSelect(HouseRecordInfoActivity.this, "与业主关系", relationList);
                relationSelect.show();
                relationSelect.setOnSelectListener(new SheetSelect.OnSelectListener() {
                    @Override
                    public void select(Object o) {
                        Map<String, Object> map = (Map<String, Object>) o;
                        relationSelect.dismiss();
                        binding.linkRelation.setText(map.get("valueName").toString());
                        jsonObject.put("relation", map.get("valuel").toString());
                    }
                });
                break;
            default:
                break;
        }
    }

    private void getDiction() {
        //
        String url;
        if (getIntent().getStringExtra("type").equals("rent")) {
            url = ApiConfig.RECORD_RENT_DICTIONARY;
        } else {
            url = ApiConfig.RECORD_SHS_DICTIONARY;
        }
        OkHttpUtils.get()
                .url(url.concat(getIntent().getStringExtra("code")))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(HouseRecordInfoActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //房屋用途list数据字典
                            housePurpose = JSON.parseObject(data.getJSONArray("purpose").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //居室list数据字典
                            houseTypeList = JSON.parseObject(data.getJSONArray("houseTypeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //朝向list数据字典
                            faceList = JSON.parseObject(data.getJSONArray("faceList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //看房时间list数据字典
                            seeTimeList = JSON.parseObject(data.getJSONArray("seeTimeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //委托来源list数据字典
                            entrustSourceList = JSON.parseObject(data.getJSONArray("entrustSourceList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //与业主关系数据字典
                            relationList = JSON.parseObject(data.getJSONArray("relationList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });

                            //住宅室数据字典
                            residenceS = JSON.parseObject(data.getJSONArray("zhuzhai-shi").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //住宅厅数据字典
                            residenceT = JSON.parseObject(data.getJSONArray("zhuzhai-ting").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //住宅卫数据字典
                            residenceW = JSON.parseObject(data.getJSONArray("zhuzhai-wei").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //住宅厨数据字典
                            residenceC = JSON.parseObject(data.getJSONArray("zhuzhai-chu").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });

                            //公寓室数据字典
                            apartmentS = JSON.parseObject(data.getJSONArray("gongyu-shi").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //公寓厅数据字典
                            apartmentT = JSON.parseObject(data.getJSONArray("gongyu-ting").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //公寓卫数据字典
                            apartmentW = JSON.parseObject(data.getJSONArray("gongyu-wei").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //公寓厨数据字典
                            apartmentC = JSON.parseObject(data.getJSONArray("gongyu-chu").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });

                            //别墅室数据字典
                            villaS = JSON.parseObject(data.getJSONArray("bieshu-shi").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //别墅厅数据字典
                            villaT = JSON.parseObject(data.getJSONArray("bieshu-ting").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //别墅卫数据字典
                            villaW = JSON.parseObject(data.getJSONArray("bieshu-wei").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //别墅厨数据字典
                            villaC = JSON.parseObject(data.getJSONArray("bieshu-chu").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });

                            purposedict = data.getString("purpose-dict");
                            roomDict = String.valueOf(data.getInteger("room-dict"));
                            hallDict = String.valueOf(data.getInteger("hall-dict"));
                            kitchenDict = String.valueOf(data.getInteger("kitchen-dict"));
                            toiletDict = String.valueOf(data.getInteger("toilet-dict"));

                            new Thread(){
                                @Override
                                public void run() {
                                    super.run();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (purposedict!=null){
                                                if (("厂房/仓库").equals(purposedict)||("商铺").equals(purposedict)||("写字楼").equals(purposedict)){
                                                    binding.jslayout.setVisibility(View.GONE);
                                                }

                                                if (!purposedict.equals("null")){binding.housePurpose.setText(purposedict);
                                                    jsonObject.put("purpose",purposedict);
                                                }
                                            }


                                            if (!roomDict.equals("null")&&!TextUtils.isEmpty(roomDict)){
                                                apartment = roomDict+"室";
                                                jsonObject.put("room",roomDict);
                                            }
                                            if (!hallDict.equals("null")&&!TextUtils.isEmpty(hallDict)){
                                                apartment = apartment+hallDict+"厅";
                                                jsonObject.put("hall",hallDict);
                                            }
                                            if (!kitchenDict.equals("null")&&!TextUtils.isEmpty(kitchenDict)){
                                                apartment = apartment+kitchenDict+"厨";
                                                jsonObject.put("kitchen",kitchenDict);
                                            }
                                            if (!toiletDict.equals("null")&&!TextUtils.isEmpty(toiletDict)){
                                                apartment = apartment+toiletDict+"卫";
                                                jsonObject.put("toilet",toiletDict);
                                            }

                                            binding.houseType.setText(apartment);
                                        }
                                    });
                                }
                            }.start();

                        }
                    }
                });
    }

    private void submit() {
        progressDialog.show();
        String url;
        if (getIntent().getStringExtra("type").equals("rent")) {
            url = ApiConfig.RENT_SUBMIT;
            jsonObject.put("rentPrice", binding.price.getText().toString());
        } else {
            url = ApiConfig.SHS_SUBMIT;
            jsonObject.put("salePrice", binding.price.getText().toString());
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HouseRecordInfoActivity.this, response)) {
                            IconToast.showToast(HouseRecordInfoActivity.this, R.mipmap.ic_success, "保存成功", 1500);
                            finish();
                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
